package com.test.demoapp.http

import android.os.Handler
import android.os.Looper
import okhttp3.*
import java.io.IOException
import java.io.Serializable
import java.util.concurrent.TimeUnit

class OkManager private constructor() {
    private val client: OkHttpClient
    private val handler: Handler
    private val FAILED = -1
    /**
     * 请求返回的是JSON字符串
     *
     * @param jsonValue
     * @param callBack
     */
    private fun onSuccessJsonStringMethod(jsonValue: ResponseData, callBack: Fun1) {
        handler.post { callBack.onComplete(jsonValue) }
    }

    /**
     * 异步请求,请求返回Json字符串
     *
     * @param url
     * @param callback
     */
    fun httpGet(url: String, callback: Fun1) {
        val request = Request.Builder().url(url).build()
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                e.printStackTrace()
                val data = ResponseData(FAILED, e.message)
                onSuccessJsonStringMethod(data, callback)
            }

            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                if (response != null && response.isSuccessful) {
                    val data = ResponseData(response.body()!!.string())
                    data.loadUrl = url
                    onSuccessJsonStringMethod(data, callback)
                } else {
                    onSuccessJsonStringMethod(
                        ResponseData(response.code(), response.message()), callback
                    )
                }
            }
        })
    }

    //回调
    interface Fun1 {
        fun onComplete(resp: ResponseData)
    }

    class ResponseData : Serializable {
        var code: Int
        var response: String
        private var errorMsg: String?
        var loadUrl: String? = null

        constructor(code: Int, errorMsg: String?) {
            this.code = code
            response = ""
            this.errorMsg = errorMsg
        }

        constructor(response: String) {
            code = SUCCESS
            this.response = response
            errorMsg = ""
        }

    }

    companion object {
        @Volatile
        private var manager: OkManager? = null
        private const val SUCCESS = 200
        val instance: OkManager?
            get() {
                if (manager == null) {
                    synchronized(OkManager::class.java) {
                        if (manager == null) {
                            manager = OkManager()
                        }
                    }
                }
                return manager
            }
    }

    init {
        val builder = OkHttpClient.Builder()
        builder.readTimeout(10000, TimeUnit.MILLISECONDS)
        builder.writeTimeout(10000, TimeUnit.MILLISECONDS)
        builder.connectTimeout(10000, TimeUnit.MILLISECONDS)
        client = builder.build()
        handler = Handler(Looper.getMainLooper())
    }
}